package org.cfk.delaytasktutorial.job;

import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.cfk.delaytasktutorial.entity.LazyJob;
import org.cfk.delaytasktutorial.enums.LazyJobLazyLevel;
import org.cfk.delaytasktutorial.handler.LazyJobHandler;
import org.cfk.delaytasktutorial.service.LazyJobDeadLetterService;
import org.cfk.delaytasktutorial.service.LazyJobService;
import org.cfk.delaytasktutorial.service.impl.DelayQueueManager;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import org.cfk.delaytasktutorial.model.DelayedMessage;
import org.redisson.api.RDelayedQueue;

@Slf4j
@Component
@RequiredArgsConstructor
public class LazyJobExecutor {

    private final LazyJobService lazyJobService;
    private final DelayQueueManager delayQueueManager;

    @XxlJob("lazyJobExecutor")
    public void execute(String params) {
        XxlJobHelper.log("延迟任务预加载器开始执行");
        List<LazyJob> lazyJobs = lazyJobService.poll();
        
        for (LazyJob lazyJob : lazyJobs) {
            try {
                // 计算任务的延迟时间
                long delayTime = ChronoUnit.MILLIS.between(LocalDateTime.now(), lazyJob.getUtil());
                if (delayTime <= 0) {
                    delayTime = 0;
                }


                delayQueueManager.addTask(lazyJob.getWorker(), lazyJob.getContent(), lazyJob.getUtil());
                XxlJobHelper.log("任务已加入延迟队列: {}, 延迟时间: {}ms", lazyJob.getId(), delayTime);

                // 从数据库中删除任务
                lazyJobService.deleteById(lazyJob.getId());
                XxlJobHelper.log("从数据库中删除任务: {}", lazyJob.getId());
            } catch (Exception e) {
                log.error("预加载任务失败: {}", lazyJob.getId(), e);
                XxlJobHelper.log("预加载任务失败: {}, 错误: {}", lazyJob.getId(), e.getMessage());
            }
        }

        XxlJobHelper.log("延迟任务预加载器执行完成，共处理{}个任务", lazyJobs.size());
    }

}